extends InputControl

@onready var textureRect = $TextureRect
@onready var countLabel = $Label

var data
var config 
var itemType


func initItem(_data, type):
	data = _data
	config = data.config
	itemType = type
	
	var resource = config.icon
	textureRect.texture = Global.createIconAtlasTexture(resource)
	
	if data.count > 1:
		countLabel.visible = true
		countLabel.text = str(data.count)
	else:
		countLabel.visible = false
	

func onMouseHover(pos):
	var msg = getInfoMsg()
	Inventory.infoDialog.showMsg(msg, pos)


func getInfoMsg():
	var msg = ""
	if itemType == Consts.ITEM_TYPE_CONSUMABLE:
		msg = ConfigClasses.ConsumableItemTypeConfig.configsDict[config.type].infoTemplate
		if config.type == Consts.CONSUMABLE_TYPE_RECOVER_01:
			msg = msg.replace("{0}", config.hp)
			
	elif itemType == Consts.ITEM_TYPE_WEAPON:
		msg = ConfigClasses.OtherInfoTemplateConfig.configsDict[Consts.ITEMINFO_TEMPLATE_WEAPON].template
		var props = data.getProperties(Inventory.currentSelectedEntityData)
		msg = Global.replacePlaceholders(msg, props)
		
	elif itemType == Consts.ITEM_TYPE_EQUIPMENT:
		msg = ConfigClasses.OtherInfoTemplateConfig.configsDict[Consts.ITEMINFO_TEMPLATE_EQUIPMENT].template
		var props = data.getProperties()
		msg = Global.replacePlaceholders(msg, props)
	
	return msg
	
	
func onMouseHoverOut():
	Inventory.infoDialog.hide()
	

func showPopup():
	if Inventory.itemPopup: return
	
	var mousePosition = Global.getMousePosition()
	
	var template = ""
	if itemType == Consts.ITEM_TYPE_CONSUMABLE:
		template = ConfigClasses.ConsumableItemTypeConfig.configsDict[config.type].popupTemplate
	elif itemType == Consts.ITEM_TYPE_WEAPON:
		template = ConfigClasses.OtherInfoTemplateConfig.configsDict[Consts.POPUP_TEMPLATE_WEAPON].template
	elif itemType == Consts.ITEM_TYPE_EQUIPMENT:
		template = ConfigClasses.OtherInfoTemplateConfig.configsDict[Consts.POPUP_TEMPLATE_EQUIPMENT].template
		
	var menusData = Global.parseMenuConfigText2Structure(template)
	
	var inst = Global.createSceneInst(Consts.RESOURCE_UI_POPUP)
	Inventory.add_child(inst)
	inst.initAndShow(menusData, mousePosition)
	
	inst.sigClickMenuItem.connect(onPopupClickMenuItem)
	inst.sigCancelPopup.connect(onCancelPopup)
	
	Inventory.itemPopup = inst
	

func onMouseLeftButtonPressed():
	showPopup()


func onCancelPopup():
	Inventory.itemPopup = null
	pass
	
	
func onPopupClickMenuItem(name, data):
	Inventory.itemPopup = null
	
	if name == Consts.POPUP_USE and itemType == Consts.ITEM_TYPE_CONSUMABLE:
		consumableItemUse()
	elif name == Consts.POPUP_EQUIP and itemType == Consts.ITEM_TYPE_EQUIPMENT:
		equipEquipment()
	elif name == Consts.POPUP_EQUIP and itemType == Consts.ITEM_TYPE_WEAPON:
		equipWeapon()


func consumableItemUse():
	pass
	
	
func equipEquipment():
	var targetEntity = Inventory.currentSelectedEntityData
	targetEntity.equipEquipment(data)
	Inventory.reOpen()
	

func equipWeapon():
	var targetEntity = Inventory.currentSelectedEntityData
	targetEntity.equipWeapon(data)
	Inventory.reOpen()
